package com.bookyourtrek.action;

import java.sql.SQLException;

import com.bookyourtrek.model.LoginModel;
import com.bookyourtrek.model.RegisterModel;
import com.bookyourtrek.util.EmailManager;
import com.bookyourtrek.util.RuntimeSettings;
import com.bookyourtrek.util.UtilityFunctions;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @author ananda
 * New User Registration Class
 */
public class RegisterAction extends ActionSupport {
	private static final long serialVersionUID = 1L;

	private String remail;
	private String rpassword;
	private String rphone;


	public String getRphone() {
		return rphone;
	}


	public void setRphone(String rphone) {
		this.rphone = rphone;
	}


	public String getRemail() {
		return remail;
	}


	public void setRemail(String remail) {
		this.remail = remail;
	}


	public String getRpassword() {
		return rpassword;
	}


	public void setRpassword(String rpassword) {
		this.rpassword = rpassword;
	}


	/**
	 * function for new user registration 
	 * @return success
	 * @throws SQLException 
	 */
	public String register() throws SQLException {
		
		//custom validation
		//check if user already exists
		//LoginModel object
		LoginModel loginmodel = new LoginModel();
		if(loginmodel.checkEmail(remail)){
			addFieldError("alreadyregistered","User already registered, please sign in to continue.");
			return INPUT;
		}
		//custom validation end here
		
		//RegisterModel object
		RegisterModel registermodel  = new RegisterModel();
		
		//register new user
		if(registermodel.registerNewUser(remail, 
				UtilityFunctions.generateMD5(rpassword), rphone)) {
		
		//uncomment and change smtp settings before deployment
		//send mail of new account created
		EmailManager.sendMail(remail, "Welcome to bookyourtrek - trek till you break",
				"Your account is being created successfully!",
				RuntimeSettings.smtpFrom, RuntimeSettings.smtpPassword);
				
		addActionMessage("Registration successful! login to continue");
		return SUCCESS;
		}
		addActionError("Registration unsuccessful");
		return INPUT;
	}

}
